import express, { Request, Response } from "express";
import fetch from "node-fetch";
// import dotenv from "dotenv";
import cors from "cors";
import "dotenv/config";

const app = express();
const PORT = process.env.PORT || 3000;
// const AMAP_KEY = process.env.AMAP_KEY || "";

app.use(
	cors({
		origin: "*",
		credentials: false,
	})
);

interface WeatherResponse {
	status?: string;
	lives?: {
		city: string;
		weather: string;
		temperature: string;
		humidity: string;
	}[];
}

app.get("/api/weather", async (req, res) => {
	const { lng, lat } = req.query;

	if (!lng || !lat) {
		return res.status(400).json({ error: "缺少 lng 或 lat 参数" });
	}

	try {
		const weatherRes = await fetch(
			`https://${process.env.HOSTAPI}/v7/weather/now?location=${lng},${lat}&key=${process.env.APIKEY}`
		);
		const weatherData = (await weatherRes.json()) as WeatherResponse;

		res.json(weatherData);
	} catch (err) {
		res.status(500).json({ error: "服务器错误" });
	}
});

app.listen(PORT, () => {
	console.log(`✅ Server is running on http://localhost:${PORT}`);
});
